package com.unlcn.ils.sales.backend.service;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.unlcn.ils.sales.backend.bo.UserViewBO;
import com.unlcn.ils.sales.backend.constant.AutoConfConstant;
import com.unlcn.ils.sales.backend.enums.AttachAuditStatusEnum;
import com.unlcn.ils.sales.base.mapper.SaleOrderAttachMapper;
import com.unlcn.ils.sales.base.model.SaleOrderAttach;
import com.unlcn.ils.sales.base.model.SaleOrderAttachExample;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by houjianhui on 2017/8/14.
 */
@Service
public class OrderAttachServiceImpl implements OrderAttachService{

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderAttachServiceImpl.class);

    @Autowired
    private SaleOrderAttachMapper saleOrderAttachMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AutoConfConstant autoConfConstant;

    @Autowired
    private UserService userService;

    @Override
    public int save(String attach, Integer saleOrderId, String saleOrderCode) throws Exception {
        if (Objects.equals(attach, null) || Objects.equals(attach, "")) {
            LOGGER.info("OrderAttachServiceImpl.save param attach must not be null");
            throw new IllegalArgumentException("销售订单附件信息不能为空");
        } else if (Objects.equals(saleOrderId, null) || Objects.equals(saleOrderId, 0)) {
            LOGGER.info("OrderAttachServiceImpl.save param saleOrderId must not be null");
            throw new IllegalArgumentException("销售订单主键不能为空");
        } else if (StringUtils.isBlank(saleOrderCode)) {
            LOGGER.info("OrderAttachServiceImpl.save param saleOrderCode must not be null");
            throw new IllegalArgumentException("销售订单编码不能为空");
        }

        // 删除历史附件信息
        deleteAttachBySaleOrderId(saleOrderId);

        // 插入最新附件信息
        List<String> attachs = JSONArray.parseArray(attach, String.class);
        if (CollectionUtils.isNotEmpty(attachs)) {
            SaleOrderAttach orderAttach = new SaleOrderAttach();
            orderAttach.setSaleOrderId(saleOrderId);
            attachs.stream().forEach(item -> {
                orderAttach.setPicKey(item);
                saleOrderAttachMapper.insertSelective(orderAttach);
            });
        }

        // 更新销售订单附件审核状态
        orderService.updateAttachAuditStatusBySaleOrderId(saleOrderId, AttachAuditStatusEnum.ORDER_SUBMIT.getValue());

        UserViewBO user = userService.getCurrentUser();

        pushSaleOrderFormBmsResult(saleOrderId, saleOrderCode, attach, user.getRealName());
        return 0;
    }

    private void pushSaleOrderFormBmsResult(Integer salesOrderId, String salesOrderCode, String picKey, String createUser) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("salesOrderId", salesOrderId);
        map.put("salesOrderCode", salesOrderCode);
        map.put("picKey", picKey);
        map.put("createUser", createUser);
        String result = HttpRequestUtil.sendHttpPost(autoConfConstant.getBms() + "api/audit/submit", map, autoConfConstant.getBmsTime());
        if (!Objects.equals(result, null)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msgCode = jsonObject.getString("messageCode");
            String msg = jsonObject.getString("message");
            Boolean success = jsonObject.getBoolean("success");
            if (!success) {
                LOGGER.info("OrderAttachServiceImpl.pushSaleOrderFormBmsResult result error");
                throw new BusinessException(msgCode, msg);
            }
        }
    }

    @Override
    public int deleteAttachBySaleOrderId(Integer saleOrderId) throws Exception {
        if (Objects.equals(saleOrderId, null) || Objects.equals(saleOrderId, "") || Objects.equals(saleOrderId, 0)) {
            LOGGER.info("OrderAttachServiceImpl.deleteAttachBySaleOrderId param saleOrderId must not be null");
            throw new IllegalArgumentException("销售订单主键不能为空");
        }
        SaleOrderAttachExample example = new SaleOrderAttachExample();
        example.createCriteria().andSaleOrderIdEqualTo(saleOrderId).andDeleteMarkEqualTo(true);
        List<SaleOrderAttach> attaches = saleOrderAttachMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(attaches)) {
            attaches.stream().forEach(item -> {
                item.setDeleteMark(false);
                saleOrderAttachMapper.updateByPrimaryKeySelective(item);
            });
        }
        return 0;
    }
}
